<?php

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Models\InviteSettlementCollect;
use App\Models\InviteSettlement;
use Illuminate\Support\Facades\Redis;
use App\Models\InviteRelationLog;

class SettlementQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $page_size = 100;
    protected $params;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        set_time_limit(0);
        $action = $this->params['action'];
        $config_data = $this->params['data'];
        $this->$action($config_data);

        return true;
    }

    /**
     * @desc 创建结算记录
     * @param $params
     * @return bool
     */
    private function create_invite_settlement($params)
    {
        $total = InviteSettlementCollect::count();

        $total_page = (int)ceil($total/$this->page_size);
        $settlement_week = date('W', ($params['next_settlement_time']));
        $settlement_month = date('Ym', $params['next_settlement_time']);

        $activity_strategy = [];
        $params['activity_strategy'] = json_decode($params['activity_strategy'], true);
        foreach($params['activity_strategy'] as $strategy) {
            $activity_strategy[$strategy['reward_user']] = $strategy;
        }
        
        for($i=1;$i<=$total_page;$i++) {
            $offset = ($i - 1) * $this->page_size;
            $invite_collect_list = InviteSettlementCollect::skip($offset)->take($this->page_size)->orderBy('id', 'ASC')->get()->toArray();
            if(empty($invite_collect_list)) {
                return true;
            }

            foreach($invite_collect_list as $invite_collect) {
                // 获取该用户的角色、会员角色
                $user_info = User::where(['id' => $invite_collect['uid'], 'status' => 1])->first();
                if(empty($user_info)) {
                    continue;   // 用户状态不正常不处理
                }

                // 处理用户的身份
                if($user_info->role == 1) {
                    $reward_user = 3;
                } elseif ($user_info->membership == 1) {
                    $reward_user = 2;
                } else {
                    $reward_user = 1;
                }


                $where_arr = [['reg_time', '>=', $params['last_settlement_time']], ['reg_time', '<=', $params['next_settlement_time']], ['invite_uid', '=', $invite_collect['uid']]];
                $invite_number = InviteRelationLog::where($where_arr)->count();
                // 处理奖励金额

                $reward_amount = 0;
                if(isset($activity_strategy[$reward_user])) {
                    $reward_units = $activity_strategy[$reward_user]['reward_units'];
                    foreach($activity_strategy[$reward_user]['list'] as $value) {
                        if($value['start_number'] <= $invite_number && $value['end_number'] >= $invite_number) {
                            $reward_amount = $reward_units == 1 ? (int)$value['reward_amount'] : ((int)$value['reward_amount'] * $invite_number);
                        }
                    }
                }

                $where_arr = ['uid' => $invite_collect['uid'], 'settlement_type' => $params['settlement_type'], 'start_time' => $params['last_settlement_time'], 'end_time' => $params['next_settlement_time']];

                $settlement_data = [
                    'uid' => $invite_collect['uid'],
                    'status' => 0,
                    'settlement_time' => 0,
                    'invite_number' => $invite_number,
                    'start_time' => $params['last_settlement_time'],
                    'end_time' => $params['next_settlement_time'],
                    'settlement_type' => $params['settlement_type'],
                    'settlement_week' => $params['settlement_type'] == 1 ? $settlement_week : 0,
                    'settlement_month' => $settlement_month,
                    'reward_amount' => $reward_amount,
                    'created_at' => time()
                ];

                if(!InviteSettlement::where($where_arr)->first(['id'])) {
                    InviteSettlement::insert($settlement_data);
                }

            }
        }
        return true;
    }
}
